package com.printeverywhere.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.printeverywhere.delegator.AuctionBidsServiceDelegator;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.ItemsServiceDelegator;
import com.printeverywhere.delegator.ItemsWatchListServiceDelegator;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.AuctionBids;
import com.printeverywhere.dto.ItemNote;
import com.printeverywhere.dto.ItemOffers;
import com.printeverywhere.dto.Items;
import com.printeverywhere.dto.ItemsWatchlist;
import com.printeverywhere.dto.Itemtype;
import com.printeverywhere.dto.User;
import com.printeverywhere.dto.UserRating;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.DateUtil;
import com.printeverywhere.util.SearchCriteria;
import com.printeverywhere.util.SearchListCriteria;
import com.printeverywhere.util.SessionUtil;

public class AdvertisingAction extends FrontBaseSupport implements ServletRequestAware{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private User user;

	private List<Items> itemsList = new ArrayList<Items>();

	private List<Items> itemsListTemp = new ArrayList<Items>();

	private SearchListCriteria searchListCriteria = new SearchListCriteria( );

	private SearchCriteria searchCriteria = new SearchCriteria();

	private HttpServletRequest request;

	private Logger logger = Logger.getLogger(AdvertisingAction.class);

	private Itemtype itemtype;

	private String action;

	public AdvertisingAction(){
		super(true, false);
		setMyAccount(true);
	}

	public String execute(){
		try {
			if(itemsList.size() > 0){
				itemsList.clear();
			}
			if(itemsListTemp.size() > 0){
				itemsListTemp.clear();
			}
			user = SessionUtil.getUser(request);
			itemtype = (Itemtype) CommonFunctionDelegator.getObjectById(AdminConstants.ID, 5, Itemtype.class);
			if(searchCriteria.getAttributeNames().size() > 0)
				searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute(AdminConstants.USERID, user);
			searchCriteria.setAttribute(AttributeConstants.ITEMTYPE, itemtype);
			itemsListTemp = ItemsServiceDelegator.getList(searchCriteria);
			getMyAdvertising(itemsListTemp);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return INPUT;
		}
		return SUCCESS;
	}

	public String watchingOthers(){
		try {
			if(itemsList.size() > 0){
				itemsList.clear();
			}
			if(itemsListTemp.size() > 0){
				itemsListTemp.clear();
			}
			user = SessionUtil.getUser(request);
			searchListCriteria.removeAllAttribute();
			searchListCriteria.setAttribute(AttributeConstants.USER, new Object[]{user, SearchListCriteria.EQ});
			List<ItemsWatchlist> itemsWatchList = ItemsWatchListServiceDelegator.getList(searchListCriteria);
			for (Iterator<ItemsWatchlist> iterator = itemsWatchList.iterator(); iterator
					.hasNext();) {
				ItemsWatchlist itemsWatchlistDTO = (ItemsWatchlist) iterator
						.next();
				Items items = itemsWatchlistDTO.getItems();
				if((items.getUserId() != user) && (items.getItemtype().getId() == 5)){
					itemsListTemp.add(items);
				}

			}
			getMyAdvertising(itemsListTemp);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return INPUT;
		}
		return SUCCESS;
	}

	public String deleteWatchingOthers(){
		try {
			user = SessionUtil.getUser(request);
			if(request.getParameter("cid") != null){
				int id = Integer.parseInt(request.getParameter("cid"));
				Items items = ItemsServiceDelegator.getItemsById(id);
				searchListCriteria.removeAllAttribute();
				searchListCriteria.setAttribute(AttributeConstants.USER, new Object[]{user, SearchListCriteria.EQ});
				searchListCriteria.setAttribute(AttributeConstants.ITEMS, new Object[]{items, SearchListCriteria.EQ});
				ItemsWatchlist itemsWatchlist = ItemsWatchListServiceDelegator.getList(searchListCriteria).size() > 0 ?ItemsWatchListServiceDelegator.getList(searchListCriteria).get(AdminConstants.ZERO_NUMBER) : null;
				if(itemsWatchlist != null){
					CommonFunctionDelegator.GeneralDelete(itemsWatchlist);
				}else{
					addActionError("Item not deleted.".intern());
					return INPUT;
				}
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage());
			return INPUT;
		}
		return SUCCESS;
	}

	public String deleteMyAdvertising() throws Exception{
		try {
			if(itemsList.size() > 0){
				itemsList.clear();
			}
			if(itemsListTemp.size() > 0){
				itemsListTemp.clear();
			}
			user = SessionUtil.getUser(request);
			itemtype = (Itemtype) CommonFunctionDelegator.getObjectById(AdminConstants.ID, 5, Itemtype.class);
			ItemsServiceDelegator.deleteItems(request);
			if(request.getParameter("action")!= null){
				action = request.getParameter("action");
			}

			if(searchListCriteria.getAttributeNames().size() > 0)
				searchListCriteria.removeAllAttribute();
			if(action.equals("myadvertisements.htm")){
				searchListCriteria.setAttribute(AdminConstants.USERID, new Object[]{user, SearchListCriteria.EQ});
			}
			if(action.equals("watchingothers.htm")){
				searchListCriteria.setAttribute(AdminConstants.USERID, new Object[]{user, SearchListCriteria.NE});
			}
			searchListCriteria.setAttribute(AttributeConstants.ITEMTYPE, new Object[]{itemtype, SearchListCriteria.EQ});
			itemsListTemp = ItemsServiceDelegator.getListBySearchListCriteria(searchListCriteria);

			getMyAdvertising(itemsListTemp);
		}catch(Exception e) {
			if(searchListCriteria.getAttributeNames().size() > 0)
				searchListCriteria.removeAllAttribute();
			if(action.equals("myadvertisements.htm")){
				searchListCriteria.setAttribute(AdminConstants.USERID, new Object[]{user, SearchListCriteria.EQ});
			}
			if(action.equals("watchingothers.htm")){
				searchListCriteria.setAttribute(AdminConstants.USERID, new Object[]{user, SearchListCriteria.NE});
			}
			searchListCriteria.setAttribute(AttributeConstants.ITEMTYPE, new Object[]{itemtype, SearchListCriteria.EQ});
			itemsListTemp = ItemsServiceDelegator.getListBySearchListCriteria(searchListCriteria);

			getMyAdvertising(itemsListTemp);
			return INPUT;
		}
		return SUCCESS;
	}


	public void getMyAdvertising(List<Items> itemsListTemp) throws Exception{
		try {
			for (Iterator<Items> iterator = itemsListTemp.iterator(); iterator.hasNext();) {
				Items type = (Items) iterator.next();
				if(type.getBids().size()>0)
					if((type.getStatus().getId() == AdminConstants.ONE_NUMBER))
						continue;
				AuctionBids auctionBids = new AuctionBids();
				ItemNote itemNote = new ItemNote();
				searchListCriteria.removeAllAttribute();
				searchListCriteria.setAttribute(AttributeConstants.ITEMS, new Object[]{type, SearchListCriteria.EQ});
//				searchListCriteria.setAttribute(AttributeConstants.USER, new Object[]{user, SearchListCriteria.EQ});
				List<ItemsWatchlist> itemsWatchList = ItemsWatchListServiceDelegator.getList(searchListCriteria);
				type.setNoOfWatches(itemsWatchList.size());
				String[] giftIcon;
				giftIcon = type.getGiftIcon().split(AdminConstants.SEMICOLON);
				if(giftIcon.length > 0)
					type.setGiftIcon(giftIcon[0]);
				if((type.getQuantity() != null) && (type.getSold() != null))
					type.setAvailable(type.getQuantity() - type.getSold());
				auctionBids = AuctionBidsServiceDelegator.getMaxBidder(type.getItemId());
				if(auctionBids != null){
					type.setBidder(auctionBids.getUser());
					type.setWinningBid(auctionBids);
				}else{
					type.setBidder(new User());
					type.setWinningBid(auctionBids);
				}
				if(type.getEndTime().before(DateUtil.getTodaysDate())){
					type.setClosed(true);
				}else{
					type.setClosed(false);
				}
				if(getRating(type.getUserId().getId()) != null){
					type.setSellerRating(getRating(type.getUserId().getId()));
				}
				/* retrieving note */
				searchCriteria.removeAllAttribute();
				searchCriteria.setAttribute(AttributeConstants.ITEMS, type);
				searchCriteria.setAttribute(AttributeConstants.USER, user);
				itemNote = (ItemNote) ((CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, ItemNote.class)).size() > 0 ? CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, ItemNote.class).get(AdminConstants.ZERO_NUMBER) : null);
				if(itemNote != null){
					type.setItemNote(itemNote);
				}
				itemsList.add(type);
			}
		} catch (Exception e) {
			throw e;
		}
	}

	public UserRating getRating(int userId){
		UserRating rating = new UserRating();
		searchCriteria.removeAllAttribute();
		searchCriteria.setAttribute("ratedUser.id", userId);
		List<UserRating> ratingList = (List<UserRating>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, UserRating.class);
		rating = ratingList.size() > 0 ? ratingList.get(0) : null;
		if(rating != null){
			return rating;
		}
		return null;
	}
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<Items> getItemsList() {
		return itemsList;
	}

	public void setItemsList(List<Items> itemsList) {
		this.itemsList = itemsList;
	}

	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}
}
